import request from '@/http/request'
import store from '@/store'
import {ElMessage} from 'element-plus'

export default [
  {
    path: '/',
    name: 'IndexLayout',
    component: () => import('@/components/layouts/IndexLayout'),
    redirect: '/auth/login',
    children: [
      {
        path: 'index',
        name: 'Index',
        component: () => import('@/views/Index'),
        meta: {
          title: '首页'
        }
      }
    ]
  },
  {
    path: '/auth',
    name: 'AuthLayout',
    component: () => import('@/components/layouts/AuthLayout'),
    redirect: '/auth/login',
    children: [
      {
        path: 'login',
        name: 'Login',
        component: () => import('@/views/auth/Login'),
        meta: {title: '用户登陆'}
      },
      {
        path: 'reg',
        name: 'Reg',
        component: () => import('@/views/auth/Reg'),
        meta: {title: '用户注册'}
      },
      {
        path: 'active/:token',
        name: 'Active',
        component: () => import('@/views/auth/Active'),
        meta: {title: '用户激活'}
      }
    ]
  },
  {
    path: '/home',
    name: 'HomeLayout',
    component: () => import('@/components/layouts/HomeLayout'),
    redirect: '/home/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/home/Dashboard'),
        meta: {title: '仪表盘'}
      },
      {
        path: 'spending',
        name: 'Spending',
        component: () => import('@/views/home/Spending'),
        meta: {title: '我的支出'}
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('@/views/home/Profile'),
        meta: {title: '我的资料'}
      },
      {
        path: 'updatePassword',
        name: 'UpdatePassword',
        component: () => import('@/views/home/UpdatePassword'),
        meta: {title: '修改密码'}
      }
    ],
    beforeEnter(to, from, next) {
      request.getUserInfo().then(res => {
        if (res.data.status === 200) {
          store.commit('userInfo', res.data.result.user)
          next()
        }
      }).catch(err => {
        console.log('Token失效')
        console.log(err.message)
        if (err.response.status === 401) {
          store.commit('token', null)
          ElMessage.error('您的登陆状态已失效，请重新登陆')
        }
        next({name: 'Login'})
      })
    }
  }
]